package com.example.chapter06;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter06.util.FileUtil;
import com.example.chapter06.util.ToastUtil;

import java.io.File;
import java.io.IOException;

public class FileWriteActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private CheckBox ck_married;

    private String path;
    private TextView tv_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_write);

        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        ck_married = findViewById(R.id.ck_married);
        tv_text = findViewById(R.id.tv_text);
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String name = et_name.getText().toString();
        String age = et_age.getText().toString();
        String height = et_height.getText().toString();
        String weight = et_weight.getText().toString();

        if(v.getId() == R.id.btn_save){
            StringBuilder sb = new StringBuilder();
            sb.append("姓名:").append(name);
            sb.append("\n年龄:").append(age);
            sb.append("\n身高:").append(height);
            sb.append("\n体重:").append(weight);
            sb.append("\n婚否:").append(ck_married.isChecked()? "是":"否");

            String directory = null;
            String fileName = System.currentTimeMillis() + ".txt";

            //外部存储的私有空间  卸载app后会消失 外部存储的空间较大
            directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
            //外部存储的公共空间 卸载app后不会消失
            directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            //内部存储私有空间 卸载app会消失  但是内部存储私有空间比较小
            directory = getFilesDir().toString();


            path = directory + File.separatorChar + fileName;

            Log.d("liu",path);
            try {
                FileUtil.saveText(path,sb.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            ToastUtil.show(this,"保存成功");
        }

        if(v.getId() == R.id.btn_read){
            try {
                String text = FileUtil.openText(path);
                tv_text.setText(text);
            } catch (IOException e) {
                Log.e("liu","当前文件不存在");
            }
        }
    }
}